package com.carlinfo.common.util;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class EncryptUtil
{
	Logger logger = LogManager.getLogger();
	private RegexUtil regexutil = new RegexUtil();
	private String split = "$";
	private String alth = "sha256";

	/**
	 * 加密的方法
	 * 
	 * @param source
	 * @return
	 */
	private String encodeStr(String source)
	{
		this.logger.info("--encodeStr--");
		/**
		 * 生成随机盐
		 */
		String randSalt = regexutil.proccedStr(32, "2");
		/**
		 * 加密
		 */
		String encodeStr = DigestUtils.sha256Hex(randSalt + source);
		/**
		 * 返回值为：sha256$evmsf4xp601ig0pg38tniwgthqacb6sw$91fed22433cb5bca3139bac7e8ff537b90c9a526f849268f5c241d5600766b8b
		 */
		return alth + split + randSalt + split + encodeStr;
	}

	/**
	 * 
	 * @param source明文
	 * @param souEncodeStr根据原来的明文加密后的信息
	 * @return true:相同,false:表示不相同
	 */
	public boolean check(String source, String souEncodeStr)
	{
		String[] resStr = souEncodeStr.split("\\$");
		if (resStr.length != 3)
		{
			return false;
		}
		/* 给32位随机盐:得用原来的盐 */
		String randSalt = resStr[1];
		/*
		 * encodeStr===sha256(随机盐+明文) 随机盐+明文
		 */
		String encodeStr = DigestUtils.sha256Hex(randSalt + source);
		/*
		 * sha256$随机盐$sha256(随机盐+明文)
		 * sha256$evmsf4xp601ig0pg38tniwgthqacb6sw$91fed22433cb5bca3139bac7e8ff537b90c9a526f849268f5c241d5600766b8b
		 * 拿着明文重新按照流程又拼装了一遍
		 */
		String resultEncodeRes = alth + split + randSalt + split + encodeStr;
		/* 拿着拼装的结果比对原来的结果就可以 */
		return resultEncodeRes.equalsIgnoreCase(souEncodeStr);
	}

	/**
	 * 测试
	 * 
	 * @param args
	 */
	public static void main(String[] args)
	{
		EncryptUtil encryptUtil = new EncryptUtil();
		/* 加密---设置密码 */
		String source = "111111";
		String encodeStr = encryptUtil.encodeStr(source);
		System.out.println("==encodeStr==>" + encodeStr);
		/* 验证:登陆 */
		boolean flag = encryptUtil.check("111111", encodeStr);
		System.out.println("==flag==>" + flag);
	}
}
